package com.zbkj.service.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.zbkj.common.model.agent.UserAgent;
import com.zbkj.common.model.city.CityRegionEntity;
import com.zbkj.common.request.*;
import com.github.pagehelper.PageHelper;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.URLUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zbkj.common.exception.AppException;

import com.zbkj.common.result.CommonResult;
import com.zbkj.common.result.CommonResultCode;
import com.zbkj.common.utils.CrmebDateUtil;
import com.zbkj.common.model.agent.BrandRegion;
import com.zbkj.service.dao.BrandRegionDao;
import com.zbkj.service.service.BrandRegionService;

import com.zbkj.common.response.BrandRegionPageDataResponse;
import com.zbkj.common.response.BrandRegionDetailResponse;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zbkj.service.service.CityRegionService;
import com.zbkj.service.util.BrandUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
* @author Caiyc
* @description BrandRegionServiceImpl 接口实现
* @date 2025-09-01
*/
@Service
public class BrandRegionServiceImpl extends ServiceImpl<BrandRegionDao, BrandRegion> implements BrandRegionService {

    @Resource
    private BrandRegionDao dao;
    @Autowired
    private CityRegionService cityRegionService;

    @Override
    public Boolean create(BrandRegionSaveRequest brandRegionSaveRequest) {
        BrandRegion brandRegion = new BrandRegion();
        BeanUtils.copyProperties(brandRegionSaveRequest, brandRegion, "id");
        brandRegion.setBrandId(BrandUtil.getBrandIdByUrl());

        if (brandRegionSaveRequest.getRegionType() < 4) {
            throw new AppException(CommonResultCode.VALIDATE_FAILED, "只能添加村和小区等区域");
        }
        if (brandRegionSaveRequest.getRegionType().equals(4)) {
            // 上级为街道
            brandRegion.setLevel(5);
        } else if (brandRegionSaveRequest.getRegionType().equals(5)) {
            // 上级为村
            brandRegion.setLevel(6);
        }
//        brandRegion.setDetails(getRegion(brandRegionSaveRequest));
        boolean save = save(brandRegion);
        if (!save) {
            throw new AppException(CommonResultCode.VALIDATE_FAILED, "添加失败");
        }
        return save;
    }

    private String getRegion(BrandRegionSaveRequest brandAgentItemSaveRequest) {
        if(brandAgentItemSaveRequest.getRegionType().equals(5)){
            // 上级是村
            return brandAgentItemSaveRequest.getParentName();
        } else {
            List<String> regionNameList = new ArrayList<>();
            if (StrUtil.isNotBlank(brandAgentItemSaveRequest.getProvince())) {
                regionNameList.add(brandAgentItemSaveRequest.getProvince());
            }
            if (StrUtil.isNotBlank(brandAgentItemSaveRequest.getCity())) {
                regionNameList.add(brandAgentItemSaveRequest.getCity());
            }
            if (StrUtil.isNotBlank(brandAgentItemSaveRequest.getDistrict())) {
                regionNameList.add(brandAgentItemSaveRequest.getDistrict());
            }
            if (StrUtil.isNotBlank(brandAgentItemSaveRequest.getStreet())) {
                regionNameList.add(brandAgentItemSaveRequest.getStreet());
            }
//        if (StrUtil.isNotBlank(request.getTribe())) {
//            regionNameList.add(request.getTribe());
//        }
//        if (StrUtil.isNotBlank(request.getCommunity())) {
//            regionNameList.add(request.getCommunity());
//        }
            return CollUtil.join(regionNameList, "/");
        }
    }

    /**
     * 分页查询品牌商城市区域
     *
     * @param request          请求参数
     * @param pageParamRequest 分页类参数
     * @return List<BrandRegion>
     * @author Caiyc
     * @since 2025-09-01
     */
    @Override
    public List<BrandRegionPageDataResponse> getList(BrandRegionSearchRequest request, PageParamRequest pageParamRequest) {
        PageHelper.startPage(pageParamRequest.getPage(), pageParamRequest.getLimit());

        LambdaQueryWrapper<BrandRegion> lambdaQueryWrapper = Wrappers.lambdaQuery();
        lambdaQueryWrapper.eq(BrandRegion::getBrandId, BrandUtil.getBrandIdByUrl());
        lambdaQueryWrapper.eq(BrandRegion::getIsDel, false);
        if (StrUtil.isNotBlank(request.getName())) {
            lambdaQueryWrapper.like(BrandRegion::getName, request.getName());
        }
//        if (StrUtil.isNotBlank(request.getDisId())) {
//            lambdaQueryWrapper.eq(BrandRegion::getDisId, request.getDisId());
//        }

        if (StrUtil.isNotBlank(request.getParentId()) && request.getLevel() != null) {
            if (request.getLevel().equals(5)) {
                lambdaQueryWrapper.eq(BrandRegion::getDisId, request.getParentId());
                lambdaQueryWrapper.eq(BrandRegion::getParentId, 0);
            }
            if (request.getLevel().equals(6)) {
                lambdaQueryWrapper.eq(BrandRegion::getParentId, Long.parseLong(request.getParentId()));
            }
        }

//        if (request.getParentId() != null && request.getParentId() > 0) {
//        } else {
//            lambdaQueryWrapper.eq(BrandRegion::getParentId, 0);
//        }

        lambdaQueryWrapper.orderByDesc(BrandRegion::getCreateTime);
        List<BrandRegion> brandRegions = dao.selectList(lambdaQueryWrapper);
        List<BrandRegionPageDataResponse> brandRegionResponses = new ArrayList<>();

        brandRegions.stream().forEach(x->{
            BrandRegionPageDataResponse brandRegionResponse = new BrandRegionPageDataResponse();
            BeanUtils.copyProperties(x, brandRegionResponse);
            brandRegionResponses.add(brandRegionResponse);
        });
        return brandRegionResponses;
    }

    /**
    * 修改品牌商城市区域
    * @param request
    * @return
    */
    @Override
    public boolean update(BrandRegionSaveRequest request) {
        if (ObjectUtil.isNull(request.getId()) || request.getId() < 1) {
            throw new AppException(CommonResultCode.VALIDATE_FAILED, "请传入品牌商城市区域ID");
        }
        getByIdException(request.getId());
        BrandRegion brandRegion = new BrandRegion();
        BeanUtils.copyProperties(request, brandRegion);
        return updateById(brandRegion);
    }

    private BrandRegion getByIdException(Long id) {
        BrandRegion brandRegion = getById(id);
        if (ObjectUtil.isNull(brandRegion)) {
            throw new AppException("品牌商城市区域不存在");
        }
        if (brandRegion.getIsDel()) {
            throw new AppException("品牌商城市区域不存在");
        }
        return brandRegion;
    }

    /**
    * 批量删除
    * @param idList
    * @return
    */
    @Override
    public boolean batchDelete(List<Integer> idList) {
        LambdaUpdateWrapper<BrandRegion> luw = Wrappers.lambdaUpdate();
        luw.set(BrandRegion::getIsDel, true);
        luw.in(BrandRegion::getId, idList);
        boolean update = update(luw);
        if (!update) {
            throw new AppException(CommonResultCode.ERROR.setMessage("批量删除品牌商城市区域失败"));
        }
        return true;
    }

    /**
    * 查询详情
    * @param id
    * @return
    */
    @Override
    public BrandRegionDetailResponse getDetails(Integer id) {
        LambdaQueryWrapper<BrandRegion> lqw = Wrappers.lambdaQuery();
        lqw.eq(BrandRegion::getIsDel, 0);
        lqw.eq(BrandRegion::getId, id);
        lqw.last("limit 1");
        BrandRegion brandRegion = this.getOne(lqw);
        if (ObjectUtil.isNotNull(brandRegion)) {
            BrandRegionDetailResponse response = new BrandRegionDetailResponse();
            BeanUtils.copyProperties(brandRegion, response);
            return response;
        }
        return null;
    }

    @Override
    public List<CityRegionEntity> findVillageList(String parentId, Integer level) {
        String name = null;
        if (level.equals(4)) {
            LambdaQueryWrapper<CityRegionEntity> checkWrapper = new LambdaQueryWrapper<>();
            checkWrapper.select(CityRegionEntity::getId, CityRegionEntity::getName);
            checkWrapper.eq(CityRegionEntity::getDisId, parentId);
            checkWrapper.last("limit 1");
            CityRegionEntity cityRegionEntity = cityRegionService.getOne(checkWrapper);
            if (cityRegionEntity == null) {
                return null;
            }
            name = cityRegionEntity.getName();
        }

        LambdaQueryWrapper<BrandRegion> checkWrapper = new LambdaQueryWrapper<>();
        checkWrapper.select(BrandRegion::getId, BrandRegion::getName, BrandRegion::getLevel);
        checkWrapper.eq(BrandRegion::getIsDel, 0);
        checkWrapper.eq(BrandRegion::getBrandId, BrandUtil.getBrandIdByUrl());
        if (level.equals(4)) {
//            checkWrapper.eq(BrandRegion::getStreetId, parentId);
//            checkWrapper.eq(BrandRegion::getStreet, name);
            checkWrapper.eq(BrandRegion::getDisId, parentId);
        } else if (level.equals(5)) {
            checkWrapper.eq(BrandRegion::getParentId, Long.parseLong(parentId));
        }
        checkWrapper.orderByAsc(BrandRegion::getId);
        List<BrandRegion> list = this.list(checkWrapper);
        if (CollUtil.isNotEmpty(list)) {
            return list.stream().map(item -> {
                CityRegionEntity cityRegionEntityOut = new CityRegionEntity();
                cityRegionEntityOut.setId(Long.parseLong(item.getId().toString()));
                cityRegionEntityOut.setName(item.getName());
                cityRegionEntityOut.setLevel(item.getLevel());
                cityRegionEntityOut.setDisId(item.getId().toString());
                return cityRegionEntityOut;
            }).collect(Collectors.toMap(
                    CityRegionEntity::getName,        // key: 使用 name 作为键
                    person -> person,       // value: 对象本身
                    (existing, replacement) -> existing // merge function: 键冲突时保留已存在的（即第一个）
            ))
            .values().stream().collect(Collectors.toList());
        }
        return null;
    }

}

